#!/bin/bash

# This script automates the process of building a kernel for slackware.
# Disclaimer:
#  Caveat! you're responsible for your own machine!
#  It's not my fault if you broke your machine!

## HOWTO
# 0. Unpack the kernel
# 1. cp recompile-version linux-version
# 2. cd linux-version
# 3. bzcat patch.bz2 | patch -p1
# 4. make oldconfig or make menuconfig
# 5. sh recompile-version

## Precautions
# 0. Check if there are nameclashes (i.e. new kernel doesn't obliterate a "working" kernel).
# 1. Check if lilo actually incorporated the changes.
# 2. Check if you have a backup kernel to boot from, perchance the new kernel should fail.

ARCH=$(/bin/uname -m)
PRIVATE=$ARCH # edit this for custom kernel name
KERNEL_VERSION=$(basename $PWD | grep -o -e "[0-9]\+.[0-9]\+.[0-9]\+.\?[0-9]*\$")
VERSION=$KERNEL_VERSION-$PRIVATE
KERNEL_PATH=$(dirname $PWD)

## add kernel to lilo
LILOSYMBOL=$(echo $KERNEL_VERSION | sed -e "s/\([0-9]*\)\.\?\([0-9]*\)\.\?\([0-9]*\)\.\?\([0-9]*\)/\1\2\3\4/")
LILOROOTDEV=/dev/sda1

## change the local version name
if [ -e .config ]; then
  cp -a .config .config.bak
  sed "s@\(CONFIG_LOCALVERSION=\)\".*\"@\1\"-$PRIVATE\"@" .config.bak > .config
else
  echo "No .config file"
  exit 1
fi

COMPILER="ccache gcc"

if ! [ -d $KERNEL_PATH/linux-$VERSION ]; then
  echo error: $KERNEL_PATH/linux-$VERSION
  echo "non-existent file location"
  echo "creating the necessary symlink path"
  ln -s $PWD ../linux-$VERSION
  echo "Edit your grub.conf or lilo.conf"
fi

## backup your .config elsewhere
cp -a $KERNEL_PATH/linux-$VERSION/.config /boot/config-$VERSION

## make, build, install kernel
cd $KERNEL_PATH/linux-$VERSION && \
make CC="$COMPILER" bzImage && \
make CC="$COMPILER" modules && \
make CC="$COMPILER" modules_install && \
echo "copying kernel image, map, config file" && \
cp -a $KERNEL_PATH/linux-$VERSION/arch/x86/boot/bzImage \
	/boot/bzImage-$VERSION && \
cp -a $KERNEL_PATH/linux-$VERSION/System.map /boot/System.map-$VERSION

## backup lilo.conf
cp /etc/lilo.conf /etc/lilo.conf.old

## update lilo.conf
echo -e \
"\nimage = /boot/bzImage-$VERSION\n\
  root = $LILOROOTDEV\n\
  label = sl$LILOSYMBOL\n\
  read-only\n" >> /etc/lilo.conf

## run lilo
/sbin/lilo -v3

exit 0
